package com.lagou.boot.config;

import org.springframework.core.annotation.AnnotationAwareOrderComparator;
import org.springframework.web.WebApplicationInitializer;

import javax.servlet.ServletContainerInitializer;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.HandlesTypes;
import java.lang.reflect.Modifier;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

/**
 * Servlet容器启动后, 会扫描每个jar包里面META-INF/services/javax.servlet.ServletContainerInitializer指定的实现类
 * 通过@HandlesTypes注解, 指定感兴趣的类WebApplicationInitializer, 将WebApplicationInitializer实现类(加载web.xml中的配置), 加载进来放入到set集合中
 */
@HandlesTypes(WebApplicationInitializer.class)
public class MySpringServletContainerInitializer implements ServletContainerInitializer {

    @Override
    public void onStartup(Set<Class<?>> webAppInitializerClasses, ServletContext servletContext) throws ServletException {
        List<WebApplicationInitializer> initializers = new LinkedList<>();
        if (null != webAppInitializerClasses && webAppInitializerClasses.size() > 0) {
            for (Class<?> webClass : webAppInitializerClasses) {
                if (!webClass.isInterface() && !Modifier.isAbstract(webClass.getModifiers()) && WebApplicationInitializer.class.isAssignableFrom(webClass)) {
                    try {
                        initializers.add((WebApplicationInitializer) webClass.newInstance());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        if (initializers.isEmpty()) {
            servletContext.log("No Spring WebApplicationInitializer types detected on classpath");
            return;
        }
        servletContext.log(initializers.size() + " Spring WebApplicationInitializers detected on classpath");
        AnnotationAwareOrderComparator.sort(initializers);
        for (WebApplicationInitializer initializer : initializers) {
            // 调用其onStartup方法
            initializer.onStartup(servletContext);
        }
    }

}
